﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public  static class Solution20
    {
        public static int[][] GenerateMatrix(int n)
        {
            int[][] ans = new int[n][] ;
            for (int i = 0; i < n; i++)
            {
                ans[i] = new int[n];
            }
            int total = n * n;
            int num = 1;
            int rowNum = n;
            int colNum = n;
            int left = 0;
            int top = 0;
            int right = colNum - 1;
            int bottom = rowNum - 1;
            if (n == 0)
            {
                return null;
            }
            while (num <= total)
            {

                for (int col = left; col <= right; col++)
                {
                    ans[top][col] = num;
                }
                top++;
                if (num <= total)
                {
                    for (int row = top; row <= bottom; row++)
                    {
                        ans[row][right] = num++;
                    }
                    right--;
                }
                if (num <= total)
                {
                    for (int col = right; col >= left; col--)
                    {
                        ans[bottom][col] = num++;
                    }
                    bottom--;
                }
                if (num <= total)
                {
                    for (int row = bottom; row >= top; row--)
                    {
                        ans[row][left] = num++;
                    }
                    left++;
                }
            }
            return ans;
        }
    }
}
